import __fxfx from './temp/fxfx'
// import mapv from 'mapv';     // 没法导入.包有问题.
let mapv = require('mapv');

/**
 *
 * @param
 * id : container
 * x: 120.558404    center
 * y: 27.972177
 * zoom :  缩放
 *  opt
 */
function BaiduMap(opt) {
    this._init(opt || {});
}

var p = BaiduMap.prototype;

p._init = function (opt) {
    var self = this;
    self.map = new BMap.Map(opt.id || 'container', {
        maxZoom: 22,
        enableMapClick: false
    });

    self.map.enableScrollWheelZoom(); //滚轮缩放

    self.clickCallback = opt.click;
    var x = opt.x || 120.558404;
    var y = opt.y || 27.972177;
    var zoom = opt.zoom || 12;

    var point = new BMap.Point(x, y);

    self.map.centerAndZoom(point, zoom);
    self.map.setMapStyle({
        style: 'midnight',
        styleJson: [{
                featureType: 'water',
                elementType: 'all',
                stylers: {
                    color: '#021019'
                }
            },
            {
                featureType: 'highway',
                elementType: 'geometry.fill',
                stylers: {
                    color: '#000000'
                }
            },
            {
                featureType: 'highway',
                elementType: 'geometry.stroke',
                stylers: {
                    color: '#147a92'
                }
            },
            {
                featureType: 'arterial',
                elementType: 'geometry.fill',
                stylers: {
                    color: '#000000'
                }
            },
            {
                featureType: 'arterial',
                elementType: 'geometry.stroke',
                stylers: {
                    color: '#0b3d51'
                }
            },
            {
                featureType: 'local',
                elementType: 'geometry',
                stylers: {
                    color: '#000000'
                }
            },
            {
                featureType: 'land',
                elementType: 'all',
                stylers: {
                    color: '#08304b'
                }
            },
            {
                featureType: 'railway',
                elementType: 'geometry.fill',
                stylers: {
                    color: '#000000'
                }
            },
            {
                featureType: 'railway',
                elementType: 'geometry.stroke',
                stylers: {
                    color: '#08304b'
                }
            },
            {
                featureType: 'subway',
                elementType: 'geometry',
                stylers: {
                    lightness: -70
                }
            },
            {
                featureType: 'all',
                elementType: 'labels.text.fill',
                stylers: {
                    color: '#857f7f'
                }
            },
            {
                featureType: 'all',
                elementType: 'labels.text.stroke',
                stylers: {
                    color: '#000000'
                }
            },
            {
                featureType: 'green',
                elementType: 'geometry',
                stylers: {
                    color: '#062032'
                }
            },
            {
                featureType: 'boundary',
                elementType: 'all',
                stylers: {
                    color: '#1e1c1c'
                }
            },
            {
                featureType: 'all',
                elementType: 'labels.icon',
                stylers: {
                    visibility: 'off'
                }
            },
            {
                featureType: 'all',
                elementType: 'labels.text.fill',
                stylers: {
                    color: '#2da0c6',
                    lightness: 90,
                    visibility: 'on'
                }
            }
        ]
    });

    self.map.setMinZoom(opt.minZoom || 12); //最小级别

    self.map.addEventListener('click', event => {
        console.log(event.point, event);
    });
};
//创建点.
p._createPoint = function (longitude, latitude) {
    var markerPoint = new BMap.Point(longitude, latitude);
    return markerPoint;
};
//创建图标.
p.createIcon = function (url, imgSize) {
    var icon = new BMap.Icon(url, new BMap.Size(imgSize, imgSize), {
        imageSize: new BMap.Size(imgSize, imgSize),
        imageOffset: new BMap.Size(0, 0)
    });
    return icon;
};

p.getMap = function () {
    return this.map;
};

//设置行政区域.
p.setBoundary = function (callback) {
    var that = this;
    var bdary = new BMap.Boundary();
    bdary.get('浙江省温州市瓯海区', function (rs) {
        //获取行政区域
        that.map.clearOverlays(); //清除地图覆盖物
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
            //alert('未能获取当前输入行政区域');
            return;
        }
        var pointArray = [];
        for (var i = 0; i < count; i++) {
            var ply = new BMap.Polygon(rs.boundaries[i], {
                strokeStyle: 'dashed',
                strokeWeight: 4,
                strokeColor: '#0059a3',
                fillColor: '#153b56',
                // strokeOpacity: 0.1,
                enableMassClear: false
            }); //建立多边形覆盖物

            that.map.addOverlay(ply); //添加覆盖物
            pointArray = pointArray.concat(ply.getPath());
        }
        //调整视野
        that.map.setViewport(pointArray);

        that._sourceArray = pointArray;

        if (typeof callback === 'function') {
            callback(rs);
        }
    });
};
//还原视图初始界面.
p.resetViewport = function () {
    this.map.setViewport(this._sourceArray);
};
//显示街道网格
p.showStreet = function (flag) {
    this.setStreet();

    if (flag) {
        var pointArray = [];
        for (let i = 0; i < this.polygons.length; i++) {
            const ply = this.polygons[i];
            this.map.addOverlay(ply);
            pointArray = pointArray.concat(ply.getPath());
        }
        this.map.setViewport(pointArray); //调整视野
    } else {
        for (let i = 0; i < this.polygons.length; i++) {
            const ply = this.polygons[i];
            this.map.removeOverlay(ply);
        }
    }
};

p.setStreet = function (callback) {
    if (!this.polygons) {
        this.polygons = [];
        var areas = [];
        var panqiao =
            '120.605637,27.993401;120.588389,27.982683;120.58149,27.976558;120.557344,27.966859;120.524574,27.953586;120.524574,27.953586;120.560218,27.950523;120.592414,27.946438;120.607936,27.93163;120.634383,27.941332;120.666003,27.963286;120.640707,27.983193;120.634957,27.997483;120.615985,28.002586;120.605637,27.993401';

        areas.push(panqiao);

        var colors = [
            '#fff492',
            '#fff492',
            '#98d057',
            '#e19ee6',
            '#1ad3da',
            '#ffc11d',
            '#98e800',
            '#b95817',
            '#03a9f4',
            '#39d0a4',
            '#8bbb53'
        ];

        //var pointArray = [];
        for (var i = 0; i < areas.length; i++) {
            var ply = new BMap.Polygon(areas[i], {
                strokeWeight: 2,
                strokeColor: '#ffffff'
            }); //建立多边形覆盖物
            ply.setFillColor(colors[i]); //设置多边形的填充颜色
            ply.setFillOpacity(0.35);

            this.polygons.push(ply); //加入多边形数组，以之后获取多边形边界点集
        }
        //this.map.setViewport(pointArray);    //调整视野
    }
};

p.createGrid = function (data) {
    this.polygons = [];
    var colors = [
        '#fff492',
        '#98d057',
        '#e19ee6',
        '#1ad3da',
        '#ffc11d',
        '#98e800',
        '#b95817',
        '#03a9f4',
        '#39d0a4',
        '#8bbb53'
    ];
    var z = 0;
    this.__grid_label = [];
    this.__grid_ply = [];

    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        var ply = new BMap.Polygon(item.coordinate, {
            strokeWeight: 2,
            strokeColor: '#ffffff',
            enableMassClear: false
        });
        ply.setFillColor(colors[z]);
        ply.setFillOpacity(0.35);

        item.source_color = colors[z];
        ply.pdata = item;

        var centerPoint = new BMap.Point(item.longitude, item.latitude);

        var label = new BMap.Label(item.area_name, {
            position: centerPoint,
            //enableMassClear: false
        });

        label.setStyle({
            //border: '1px solid rgb(2, 129, 190)',
            border: 'none',
            color: 'rgb(122, 208, 245)',
            // backgroundColor:'rgb(10, 68, 108)'
            backgroundColor: 'none'
        });

        this.__grid_label.push(label);
        this.__grid_ply.push(ply);

        z++;
        if (z >= colors.length) z = 0;
        this.polygons.push(ply);
        this.map.addOverlay(ply);
    }
};

p.getGridColor = function (alarmLevel) {
    switch (alarmLevel) {
        case 1:
            return 'red';
        case 2:
            return 'yellow';
        case 3:
            return 'blue';
        case 4:
            return 'green';
        default:
            return 'green';
    }
};

p.show_grid_label = function (flag) {
    if (!this.__grid_label) return;
    for (let i = 0; i < this.__grid_ply.length; i++) {
        const ply = this.__grid_ply[i];
        let item = ply.pdata;
        if (flag) {
            ply.setFillColor(this.getGridColor(item.alarm_level));
        } else {
            ply.setFillColor(item.source_color);
        }
    }

    for (let i = 0; i < this.__grid_label.length; i++) {
        const label = this.__grid_label[i];
        if (flag) this.map.addOverlay(label);
        else this.map.removeOverlay(label);
    }

};

//热力图绘制
p.hotMapCreate = function (points) {
    if (!this.isSupportCanvas()) {
        alert(
            '热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~'
        );
    }
    var heatmapOverlay = new BMapLib.HeatmapOverlay({
        radius: 5,
        opacity: 0,
        visible: false
        // gradient: {
        //     0.2:'rgb(0, 0, 255)',
        //     0.5:'rgb(200, 200, 0)',
        //     0.8:'rgb(200, 0, 0)'
        // }
    });

    this.map.addOverlay(heatmapOverlay);
    // heatmapOverlay.setDataSet({
    //     data: points,
    //     max: 100
    // });
    this._points = points;

    heatmapOverlay.hide();

    this.heatmapOverlay = heatmapOverlay;

    return heatmapOverlay;
};
//显示热力图(人口密度)
p.showHotMap = function (flag) {
    if (!this.heatmapOverlay) return;
    if (flag) {
        this.heatmapOverlay.setDataSet({
            data: this._points,
            max: 100
        });
        this.heatmapOverlay.show();
    } else {
        this.heatmapOverlay.setDataSet({
            data: []
        });
        this.heatmapOverlay.hide();
    }
};

p.toggle_FXFX_HotMap = function (flag) {
    if (flag) {
        this.show_FXFX_HotMap();
    } else {
        this.clear_FXFX_HotMap();
    }
};

//风险分析显示
p.show_FXFX_HotMap = function () {
    if (!this._rkmd_mapvLayer) {
        //var points = window.__rkmd_points;
        this.create_FXFX_HotMap(__fxfx);
    } else {
        this._rkmd_mapvLayer.show();
    }
};
//风险分析清除
p.clear_FXFX_HotMap = function () {
    if (this._rkmd_mapvLayer) {
        this._rkmd_mapvLayer.hide();
    }
};

//显示/隐藏人口密度.
p.toggle_RKMD_HotMap = function (flag) {
    if (flag) this.show_RKMD_HotMap();
    else this.hide_RKMD_HotMap();
}

p.show_RKMD_HotMap = function () {
    if (!this._hotmap_dataSet) return;
    if (!this._hotmap_mapvLayer) {
        var options = {
            size: 2,
            gradient: {
                0.25: "rgb(0,0,255)",
                0.55: "rgb(0,255,0)",
                0.85: "yellow",
                1.0: "rgb(255,0,0)"
            },
            globalAlpha: 0.6,
            max: 50,
            draw: 'heatmap'
        }

        this._hotmap_mapvLayer = new mapv.baiduMapLayer(
            this.map,
            this._hotmap_dataSet,
            options
        );
    } else {
        this._hotmap_mapvLayer.show();
    }
}

p.hide_RKMD_HotMap = function () {
    if (!this._hotmap_mapvLayer) return;
    this._hotmap_mapvLayer.hide();
}

p.create_RKMD_HotMap = function (points) {
    let data = [];
    for (const item of points) {
        let temp = {
            geometry: {
                type: 'Point',
                coordinates: [item.lng, item.lat]
            },
            count: item.count
        }
        data.push(temp)
    }

    this._hotmap_dataSet = new mapv.DataSet(data);
}

//风险分析热力图创建.
p.create_FXFX_HotMap = function (points) {
    var data = [];
    for (let i = 0; i < points.length; i++) {
        const item = points[i];
        var temp = {
            geometry: {
                type: 'Point',
                coordinates: [item.lng, item.lat]
            },
            count: item.count
        };
        data.push(temp);
    }

    var options = {
        fillStyle: 'rgba(200, 50, 50, 0.6)',
        maxSize: 10,
        max: 15,
        draw: 'bubble'
    };

    this._rkmd_dataSet = new mapv.DataSet(data);

    this._rkmd_mapvLayer = new mapv.baiduMapLayer(
        this.map,
        this._rkmd_dataSet,
        options
    );
};

p.toggle_XCTJ_HotMap = function (flag) {
    if (flag) this.show_XCTJ_HotMap();
    else this.hide_XCTJ_HotMap();
};

p.show_XCTJ_HotMap = function () {
    if (!this._xctj_mapvLayer) {
        if (!this._xctj_dataSet) return;
        var options = {
            fillStyle: 'rgba(55, 50, 250, 0.8)',
            shadowColor: 'rgba(255, 250, 50, 1)',
            shadowBlur: 20,
            size: 40,
            globalAlpha: 0.5,
            label: {
                show: true,
                fillStyle: 'white'
                // shadowColor: 'yellow',
                // font: '20px Arial',
                // shadowBlur: 10,
            },
            gradient: {
                0.25: 'rgb(0,0,255)',
                0.55: 'rgb(0,255,0)',
                0.85: 'yellow',
                1.0: 'rgb(255,0,0)'
            },
            draw: 'grid'
        };
        this._xctj_mapvLayer = new mapv.baiduMapLayer(
            this.map,
            this._xctj_dataSet,
            options
        );
    } else {
        this._xctj_mapvLayer.show();
    }
};

p.hide_XCTJ_HotMap = function () {
    if (!this._xctj_mapvLayer) return;
    this._xctj_mapvLayer.hide();
};

//巡查统计热力图创建.
p.create_XCTJ_HotMap = function (points) {
    var data = [];
    for (let i = 0; i < points.length; i++) {
        const item = points[i];
        var temp = {
            geometry: {
                type: 'Point',
                coordinates: [parseFloat(item.lng), parseFloat(item.lat)]
            },
            count: item.count
        };
        data.push(temp);
    }
    this._xctj_dataSet = new mapv.DataSet(data);
};

//添加点.
p.createMarkers = function (points, d) {
    var obj = {};

    if (points.length > 200) {
        this._randNumber(points, 200);
    }
    for (var i = 0; i < points.length; i++) {
        var point = points[i];
        if (i < 200 || point.MONITOR_ID in d || point.STATUS == 3) {
            var marker = this.createMarker(point);
            obj[point.MONITOR_ID] = marker;
        }
        //this.map.addOverlay(marker);
        //if (i >= 200) break;
    }
    return obj;
};

//随机乱序.
p._randNumber = function (arr, num) {
    if (num > arr.length) num = arr.length;
    for (let i = 0; i < num; i++) {
        let z = parseInt(arr.length * Math.random(), 10);
        let temp = arr[i];
        arr[i] = arr[z];
        arr[z] = temp;
    }
};

p.createMarker = function (point) {
    var self = this;
    var markerPoint = this._createPoint(point.LONGITUDE, point.LATITUDE);
    var status = point.STATUS;

    var imageInfo = this.getImageInfo2(status, point.DEVICE_BIG_TYPE);

    var icon = this.createIcon(imageInfo.url, imageInfo.imgSize);
    var marker = new BMap.Marker(markerPoint, {
        icon: icon
    });
    marker.cdata = point;

    if (point.STATUS == 3) {
        marker.setTop(true);
    }

    marker.addEventListener('click', event => {
        if (typeof self.clickCallback === 'function') {
            var target = event.target;
            self.clickCallback(target.cdata, target, event);
        }
    });

    return marker;
};

p.createMarkerByxy = function (longitude, latitude, url, imgSize, item) {
    var markerPoint = this._createPoint(longitude, latitude);
    var obj;
    if (url) {
        var icon = this.createIcon(url, imgSize);
        obj = {
            icon: icon
        };
    }
    var marker = new BMap.Marker(markerPoint, obj);
    if (item !== undefined) marker.cdata = item;
    return marker;
};
/**
 *
 * @param {Object} opt
 * longitude 经度 必填 int
 * latitude 纬度 必填 int
 * url  图片路径 如果不填为默认点
 * imgSize 图片大小 不填默认30
 * data 自定义属性 选填
 * click click事件
 * mouseover move事件
 * mouseout
 */
p.createMarkerPoint = function (opt) {
    var markerPoint = this._createPoint(opt.longitude, opt.latitude);
    var obj;
    if (opt.url) {
        var icon = this.createIcon(opt.url, opt.imgSize || 30);
        obj = {
            icon: icon
        };
    }
    var marker = new BMap.Marker(markerPoint, obj);
    if (opt.data !== undefined) {
        marker.cdata = opt.data;
    }

    if (typeof opt.click === 'function') {
        marker.addEventListener('click', event => {
            opt.click(event.target.cdata, event.target, event);
        });
    }

    if (typeof opt.mouseover === 'function') {
        marker.addEventListener('mouseover', event => {
            opt.mouseover(event.target.cdata, event.target, event);
        });
    }

    if (typeof opt.mouseout === 'function') {
        marker.addEventListener('mouseout', event => {
            opt.mouseout(event.target.cdata, event.target, event);
        });
    }

    return marker;
};

p.getImageInfo2 = function (STATUS, DEVICE_BIG_TYPE) {
    let url;
    let imgSize = 15;
    var name = '';
    var type = '';
    if (STATUS == 1 || STATUS == 4) {
        type = 'online';
    } else if (STATUS == 3) {
        type = 'warning';
    } else {
        type = 'offline';
    }

    if (DEVICE_BIG_TYPE == 1) {
        name = 'yangan';
    } else if (DEVICE_BIG_TYPE == 2) {
        name = 'dian';
    } else if (DEVICE_BIG_TYPE == 3) {
        name = 'shui';
    } else {
        if (DEVICE_BIG_TYPE != 4) console.warn('大类错误' + DEVICE_BIG_TYPE);
        name = 'qiti';
    }
    //TODO
    url = 'http://122.228.7.92:8888/pubinfo-restful/pubinfo/images/' + name + '-' + type + '-icon.';
    if (STATUS == 3) {
        url += 'gif';
        imgSize = 35;
    } else {
        url += 'png';
    }
    return {
        url: url,
        imgSize: imgSize
    };
};

p.getImageInfo = function (status) {
    let url;
    let imgSize = 30;
    if (status === 5 || status === 6 || status === 7 || status === 8) {
        url = `../images/state-icon${status}.gif`;
        imgSize = 35;
    } else {
        url = `../images/state-icon${status}.png`;
    }
    return {
        url: url,
        imgSize: imgSize
    };
};

p.isSupportCanvas = function () {
    if (this.__supportCanvas === undefined) {
        var elem = document.createElement('canvas');
        var flag = !!(elem.getContext && elem.getContext('2d'));
        this.__supportCanvas = flag;
    }
    return this.__supportCanvas;
};

export default BaiduMap;
